#include "data_acquisation_serial.h"
#include     <stdio.h>      /*标准输入输出定义*/
#include     <stdlib.h>     /*标准函数库定义*/
#include     <unistd.h>     /*Unix 标准函数定义*/
#include     <sys/types.h>
#include     <sys/stat.h>
#include     <fcntl.h>      /*文件控制定义*/
#include     <termios.h>    /*PPSIX 终端控制定义*/
#include     <errno.h>      /*错误号定义*/
#include "main.h"





data_acquisation::data_acquisation(QObject *parent) :
    QThread(parent)
{

    COM_SETUP(tty3_fd,"/dev/ttySAC2");

    first[0]=1;
    first[1]=1;

    count[1]=0;
    count[2]=0;

}

data_acquisation::~data_acquisation()
{
    close(tty3_fd);
}


inline void data_acquisation::append(uchar count1,uchar count2)
{
    uchar i;
    this->count1=count1;
    for(i=this->count2;i<8;i++)
     AD_VALUE[this->count1][i]=0;
    this-> count2=0;
    ad_value[count2]= atoi(AD_VALUE[count2]);

}

  template <typename T>
inline void  data_acquisation::linear(T& m,T value,T n,int i)//
{
    T buf=m-value;
    if(buf< 0) ;else buf= 0-buf;
    if(first[i]) { m=value;first[i]=0;}
    else { if(buf<= n)  {m=value;count[i]=0; }
           else  {count[i]++; if(count[i]==2) {m=value;count[i]=0;} }
         }
}
void data_acquisation::run()
{
 int num;
 uchar i;
 bool error_warn=0;
int PSU_buf;
float TEM_buf;

    while(1)
    {
        num= read(tty3_fd, buf, sizeof(buf));
        if(-1== num)
        {if(!error_warn){ perror( "Com Read error") ;error_warn=1;}  }

        for(i=0;i<num;i++)
     {
      switch(buf[i])
    {
    case ('a'):
          append(0,7);

#ifdef DEBUG
          PSU_buf=(int)(ad_value[7]*0.4884-200);
          if(PSU_buf>20) PSU_buf+=positive_pressure_adjust;
          else if(PSU_buf<-20)  PSU_buf+=negative_pressure_adjust;
          else PSU_buf+=normal_pressure_adjust;
          linear(PSU,PSU_buf,1,0);

#endif
        break;
    case ('b'):
         append(1,0);

 #ifndef DEBUG
         TEM_buf= (float)(ad_value[0]*0.2442-100.0 + temperature_adjust*0.1);
        linear(TEM,TEM_buf,(float)0.2,1);

 #endif
        break;
    case ('c'):
         append(2,1);
#ifndef DEBUG

         PSU_buf=(int)(ad_value[1]*0.4884-200);
         if(PSU_buf>20) PSU_buf+=positive_pressure_adjust;
         else if(PSU_buf<-20)  PSU_buf+=negative_pressure_adjust;
         else PSU_buf+=normal_pressure_adjust;
        linear(PSU,PSU_buf,2,0);

#endif
        break;
    case ('d'):
         append(3,2);
        break;
    case ('e'):
         append(4,3);
        break;
    case ('f'):
         append(5,4);
        break;
    case ('g'):
         append(6,5);
        break;
    case ('h'):
         append(7,6);

  #ifdef DEBUG
        TEM_buf= (float)(ad_value[6]*0.2442-100.0 + temperature_adjust*0.1);
        linear(TEM,TEM_buf,(float)0.2,1);

  #endif
        break;
    default:
          AD_VALUE[count1][count2]=buf[i];//
          count2++;
        break;

      }
     }
    }
}





